package com.learning.rocketmq.optimal.throughput;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.filter.FilterContext;
import org.apache.rocketmq.common.filter.MessageFilter;
import org.apache.rocketmq.common.message.MessageExt;

import java.io.IOException;
import java.util.List;

/**
 * ClassName: MessageFilterDemo
 * Description:
 * Date: 2019/1/14 16:46 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class MessageFilterDemo {


    void consumer() throws IOException, MQClientException {


        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("MessageFilterDemo");
        consumer.setNamesrvAddr("10.0.64.106:9876;10.0.64.107:9876");
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);


        // 使用Java 代码，在服务器做消息过滤
        String filterCode = MixAll.file2String("/home/admin/MessageFilterImpl.java");
        consumer.subscribe("TopicFilter", "com.learning.rocketmq.optimal.throughput.MessageFilterDemo.MessageFilterImpl", filterCode);

        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                System.out.println(Thread.currentThread().getName() + "Receive New Messages" + msgs);
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
    }


    /**
     * 1. 实现了过滤逻辑，它是根据消息的 "SequenceId" 这个属性来过滤的
     * <p>
     * 2. 根据消息体的内容或其他特征过滤
     */
    static class MessageFilterImpl implements MessageFilter {

        @Override
        public boolean match(MessageExt msg, FilterContext context) {

            String property = msg.getUserProperty("SequenceId");
            if (property != null) {
                int id = Integer.parseInt(property);
                if ((id % 3) == 0 && (id > 10)) {
                    return true;
                }
            }

            return false;
        }
    }


}
